<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>WebSocket实时通信测试</span>
      </div>

      <!-- 连接状态 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="12">
          <el-tag :type="connectionStatus === 'connected' ? 'success' : 'danger'">
            连接状态: {{ connectionStatusText }}
          </el-tag>
        </el-col>
        <el-col :span="12">
          <el-tag type="info">在线人数: {{ onlineCount }}</el-tag>
        </el-col>
      </el-row>

      <!-- 连接控制 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="12">
          <el-button
            type="primary"
            @click="connect"
            :disabled="connectionStatus === 'connected'"
          >
            连接WebSocket
          </el-button>
          <el-button
            type="danger"
            @click="disconnect"
            :disabled="connectionStatus !== 'connected'"
          >
            断开连接
          </el-button>
        </el-col>
        <el-col :span="12">
          <el-button type="info" @click="getOnlineCount">刷新在线人数</el-button>
        </el-col>
      </el-row>

      <!-- 消息发送 -->
      <el-card style="margin-bottom: 20px;">
        <div slot="header">发送消息</div>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-input
              v-model="messageToSend"
              placeholder="请输入要发送的消息"
              @keyup.enter.native="sendMessage"
            />
          </el-col>
          <el-col :span="8">
            <el-button
              type="primary"
              @click="sendMessage"
              :disabled="connectionStatus !== 'connected'"
            >
              发送消息
            </el-button>
          </el-col>
        </el-row>
      </el-card>

      <!-- 向指定用户发送消息 -->
      <el-card style="margin-bottom: 20px;">
        <div slot="header">向指定用户发送消息</div>
        <el-row :gutter="20" style="margin-bottom: 10px;">
          <el-col :span="8">
            <el-select
              v-model="selectedUserId"
              placeholder="请选择目标用户"
              style="width: 100%;"
              @focus="refreshOnlineUsers"
            >
              <el-option
                v-for="user in onlineUsers"
                :key="user.userId"
                :label="user.userId"
                :value="user.userId"
                :disabled="user.userId === userId"
              >
                <span>{{ user.userId }}</span>
                <span v-if="user.userId === userId" style="color: #999; margin-left: 5px;">(当前用户)</span>
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input
              v-model="userMessage"
              placeholder="请输入要发送的消息"
              @keyup.enter.native="sendToUser"
            />
          </el-col>
          <el-col :span="4">
            <el-button
              type="success"
              @click="sendToUser"
              :disabled="!selectedUserId || !userMessage.trim()"
            >
              发送
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-tag type="info" size="small">
              当前在线用户数: {{ onlineUsers.length }}
            </el-tag>
            <el-button
              type="text"
              size="small"
              @click="refreshOnlineUsers"
              style="margin-left: 10px;"
            >
              刷新用户列表
            </el-button>
          </el-col>
        </el-row>
      </el-card>

      <!-- 广播消息 -->
      <el-card style="margin-bottom: 20px;">
        <div slot="header">广播消息（管理员功能）</div>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-input
              v-model="broadcastMessage"
              placeholder="请输入广播消息"
              @keyup.enter.native="sendBroadcast"
            />
          </el-col>
          <el-col :span="8">
            <el-button type="warning" @click="sendBroadcast">发送广播</el-button>
          </el-col>
        </el-row>
      </el-card>

      <!-- 消息记录 -->
      <el-card>
        <div slot="header">
          <span>消息记录</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="clearMessages">
            清空记录
          </el-button>
        </div>
        <div class="message-container">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message-item', message.type]"
          >
            <span class="message-time">{{ message.time }}</span>
            <span class="message-content">{{ message.content }}</span>
          </div>
          <div v-if="messages.length === 0" class="no-message">
            暂无消息记录
          </div>
        </div>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import { getOnlineCount, getOnlineUsers, sendMessageToUser, sendBroadcastMessage } from '@/api/websocket'

export default {
  name: 'WebSocketTest',
  data() {
    return {
      websocket: null,
      connectionStatus: 'disconnected', // disconnected, connecting, connected
      messageToSend: '',
      broadcastMessage: '',
      userMessage: '',
      selectedUserId: '',
      messages: [],
      onlineCount: 0,
      onlineUsers: [],
      userId: null
    }
  },
  computed: {
    connectionStatusText() {
      switch (this.connectionStatus) {
        case 'disconnected':
          return '未连接'
        case 'connecting':
          return '连接中...'
        case 'connected':
          return '已连接'
        default:
          return '未知状态'
      }
    }
  },
  mounted() {
    // 获取当前用户信息
    this.userId = this.$store.getters.user?.id || 'user_' + Date.now()
    this.getOnlineCount()
    this.refreshOnlineUsers()
  },
  beforeDestroy() {
    this.disconnect()
  },
  methods: {
    connect() {
      if (this.websocket) {
        this.disconnect()
      }

      this.connectionStatus = 'connecting'
      this.addMessage('system', '正在连接WebSocket服务器...')

      // 构建WebSocket URL
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const host = window.location.hostname
      const port = process.env.NODE_ENV === 'development' ? '8998' : window.location.port
      const wsUrl = `${protocol}//${host}:${port}/websocket/${this.userId}`

      try {
        this.websocket = new WebSocket(wsUrl)

        this.websocket.onopen = this.onWebSocketOpen
        this.websocket.onmessage = this.onWebSocketMessage
        this.websocket.onclose = this.onWebSocketClose
        this.websocket.onerror = this.onWebSocketError

      } catch (error) {
        this.addMessage('error', '连接失败: ' + error.message)
        this.connectionStatus = 'disconnected'
      }
    },

    disconnect() {
      if (this.websocket) {
        this.websocket.close()
        this.websocket = null
      }
      this.connectionStatus = 'disconnected'
    },

    onWebSocketOpen(event) {
      this.connectionStatus = 'connected'
      this.addMessage('system', 'WebSocket连接成功！')
      this.getOnlineCount()
      this.refreshOnlineUsers()
    },

    onWebSocketMessage(event) {
      this.addMessage('receive', event.data)
    },

    onWebSocketClose(event) {
      this.connectionStatus = 'disconnected'
      this.addMessage('system', 'WebSocket连接已关闭')
    },

    onWebSocketError(event) {
      this.connectionStatus = 'disconnected'
      this.addMessage('error', 'WebSocket连接发生错误')
      console.error('WebSocket error:', event)
    },

    sendMessage() {
      if (!this.messageToSend.trim()) {
        this.$message.warning('请输入消息内容')
        return
      }

      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(this.messageToSend)
        this.addMessage('send', this.messageToSend)
        this.messageToSend = ''
      } else {
        this.$message.error('WebSocket未连接')
      }
    },

    sendToUser() {
      if (!this.selectedUserId) {
        this.$message.warning('请选择目标用户')
        return
      }

      if (!this.userMessage.trim()) {
        this.$message.warning('请输入消息内容')
        return
      }

      sendMessageToUser(this.selectedUserId, this.userMessage).then(response => {
        if (response.code === 200) {
          this.$message.success('消息发送成功')
          this.addMessage('send', `发送给 ${this.selectedUserId}: ${this.userMessage}`)
          this.userMessage = ''
        } else {
          this.$message.error('消息发送失败: ' + response.message)
        }
      }).catch(error => {
        this.$message.error('消息发送失败: ' + error.message)
      })
    },

    sendBroadcast() {
      if (!this.broadcastMessage.trim()) {
        this.$message.warning('请输入广播消息内容')
        return
      }

      sendBroadcastMessage(this.broadcastMessage).then(response => {
        if (response.code === 200) {
          this.$message.success('广播消息发送成功')
          this.addMessage('broadcast', '广播: ' + this.broadcastMessage)
          this.broadcastMessage = ''
        } else {
          this.$message.error('广播消息发送失败: ' + response.message)
        }
      }).catch(error => {
        this.$message.error('广播消息发送失败: ' + error.message)
      })
    },

    getOnlineCount() {
      getOnlineCount().then(response => {
        if (response.code === 200) {
          this.onlineCount = response.data.onlineCount
        }
      }).catch(error => {
        console.error('获取在线人数失败:', error)
      })
    },

    refreshOnlineUsers() {
      getOnlineUsers().then(response => {
        if (response.code === 200) {
          this.onlineUsers = response.data || []
          console.log('在线用户列表:', this.onlineUsers)
        }
      }).catch(error => {
        console.error('获取在线用户列表失败:', error)
        this.$message.error('获取在线用户列表失败')
      })
    },

    addMessage(type, content) {
      const now = new Date()
      const time = now.toLocaleTimeString()
      this.messages.push({
        type,
        content,
        time
      })

      // 自动滚动到底部
      this.$nextTick(() => {
        const container = document.querySelector('.message-container')
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },

    clearMessages() {
      this.messages = []
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.message-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  padding: 10px;
  background-color: #f8f9fa;
}

.message-item {
  margin-bottom: 8px;
  padding: 5px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.message-item.system {
  background-color: #e1f5fe;
  color: #0277bd;
}

.message-item.send {
  background-color: #e8f5e8;
  color: #2e7d32;
  text-align: right;
}

.message-item.receive {
  background-color: #fff3e0;
  color: #ef6c00;
}

.message-item.broadcast {
  background-color: #fce4ec;
  color: #c2185b;
}

.message-item.error {
  background-color: #ffebee;
  color: #d32f2f;
}

.message-time {
  font-size: 12px;
  color: #666;
  margin-right: 10px;
}

.message-content {
  word-break: break-word;
}

.no-message {
  text-align: center;
  color: #999;
  padding: 20px;
}
</style>

